from flask import jsonify, request, session, render_template

from models import db
from models.index import Follow
from . import user_blu


@user_blu.route("/user/follow", methods=["POST"])
def follow():
    # 从用户提交的数据中提取作者id
    action = request.json.get("action")
    news_au_id = request.json.get("user_id")
    # 从session中提取用户id
    user_id = session.get("user_id")
    if action == "do":

        # 创建follow对象
        follow = Follow(followed_id=news_au_id, follower_id=user_id)
        # 最终目标是在follow表中添加一行数据
        db.session.add(follow)
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "关注成功"
        }
        return jsonify(ret)
    elif action == "undo":
        follow = db.session.query(Follow).filter(Follow.followed_id == news_au_id,
                                                 Follow.follower_id == user_id).first()
        db.session.delete(follow)
        db.session.commit()
        ret = {
            "errno": 0,
            "errmsg": "取关成功"
        }
        return jsonify(ret)


@user_blu.route("/user/center")
def center():
    return render_template("user.html")


@user_blu.route("/user/user_base_info.html")
def user_base_info():
    return render_template("user_base_info.html")
